<template>
	<a-modal :visible="visible" width="1000px" class="delivery-note" title="退租交割单" centered @cancel="cancel" :maskClosable="false" destroyOnClose>
		<div class="tab-box">
			<div class="d-module-title">
				<!-- <b>房屋配置</b> -->
				<b>房间固定资产配置</b>
			</div>
			<div class="flex1 auto-y">
				<vxe-grid ref="grid" v-bind="gridOptions" @checkbox-change="selectChangeEvent" :sort-config="{trigger: 'cell'}" remote="true" trigger="cell"></vxe-grid>
			</div>
		</div>
		<div class="tab-box" v-if="earlyData.length">
			<div class="d-module-title">
				<b>能耗费预警</b>
				<span class="tip-text" v-color="{color: 'warning'}">
					<exclamation-circle-outlined />
					请先处理历史预警数据，将按照下表中手动补抄的读数生成对应的账单，请确认读数的正确性。
				</span>
			</div>
			<div class="flex1 auto-y">
				<vxe-grid ref="early" v-bind="earlyWarning" :data="earlyData">
					<template #feeSubject="{row}">
						{{ getID(row.feeSubjectId) }}
					</template>

					<template #openRead="{row, rowIndex}">
						<a-input-number v-if="isUpdate && inpudeShow.length && inpudeShow[rowIndex].firstRead" v-model:value="row.firstRead" :min="0" :max="row.lastRead ? row.lastRead : 99999999.99" :precision="2" placeholder="请输入" style="width: 100%"></a-input-number>
						<template v-else>
							{{ row.firstRead || '-' }}
						</template>
					</template>
					<template #endRead="{row, rowIndex}">
						<a-input-number v-if="isUpdate && inpudeShow.length && inpudeShow[rowIndex].lastRead" v-model:value="row.lastRead" :min="row.firstRead ? row.firstRead : 0" :max="99999999.99" :precision="2" placeholder="请输入" style="width: 100%"></a-input-number>
						<template v-else>
							{{ row.lastRead || '-' }}
						</template>
					</template>
				</vxe-grid>
			</div>
		</div>
		<!-- 后付费 -->
		<div class="tab-box" v-if="postpaData.length">
			<div class="d-module-title">
				<b>能耗读数</b>
				<span class="tip-text" v-color="{color: 'warning'}">
					<exclamation-circle-outlined />
					请填写退租确认读数。
				</span>
			</div>
			<div class="flex1 auto-y">
				<vxe-grid ref="postpaid" v-bind="postpaidOptions" :data="postpaData">
					<template #feeSubject="{row}">
						{{ getID(row.feeSubjectId) }}
					</template>
					<template #firstRead="{row}">
						<a-input-number v-model:value="row.firstRead" :class="{error: row.firstRead === null}" :min="0" :precision="2" :max="row.lastRead ? row.lastRead : 99999999.99" placeholder="请输入读数" style="width: 100%" />
					</template>
					<template #lastRead="{row}">
						<a-input-number v-model:value="row.lastRead" :class="{error: row.lastRead === null}" :min="row.firstRead ? row.firstRead : 0" :precision="2" :max="99999999.99" placeholder="请输入读数" style="width: 100%" />
					</template>
				</vxe-grid>
			</div>
		</div>
		<!-- 预付费 -->
		<div class="tab-box" v-if="energyList.length">
			<div class="d-module-title">
				<b>能耗读数</b>
				<span class="tip-text" v-color="{color: 'warning'}">
					<exclamation-circle-outlined />
					请填写退租确认读数。
				</span>
			</div>
			<div class="flex1 auto-y">
				<vxe-grid ref="energyGrid" v-bind="energyOptions" :data="energyList">
					<template #deviceType="{row}">{{ deviceMap[row.deviceType] }}</template>
					<template #ts="{row}">{{ row.ts || '-' }}</template>
					<template #amount="{row}">
						<a-input-number v-model:value="row.amount" :class="{error: row.amount === null}" :min="row.firstRead ? row.firstRead : 0" :max="99999999.99" :precision="2" placeholder="请输入读数" style="width: 100%" />
					</template>
				</vxe-grid>
			</div>
		</div>
		<div class="delivery-note-module" v-if="!energyList.length && !postpaData.length">
			<div class="d-module-title">
				<b>水电燃气底数(只做记录)</b>
			</div>
			<vxe-table :data="[{}]" border size="small" show-overflow>
				<vxe-column v-for="meter in modelRef.meters" :key="meter.deviceType" header-align="center">
					<template #header>
						{{ METER_DEVICE_MAP[meter.deviceType] }}
					</template>
					<template #default>
						<div class="display-flex">
							<a-input-number v-model:value="meter.read" size="small" :min="0" :precision="2" :controls="false" :bordered="false" placeholder="请输入底数" style="flex: 1" />
							<span style="align-self: center">{{ meter.suffix }}</span>
						</div>
					</template>
				</vxe-column>
			</vxe-table>
		</div>
		<div>
			<div class="d-module-title">
				<b>备注</b>
			</div>
			<div>
				<a-textarea v-model:value="modelRef.comment" show-count :maxlength="100" placeholder="请输入备注" />
			</div>
		</div>
		<div>
			<div class="d-module-title">
				<b>附件</b>
			</div>
			<div class="width-33">
				<a-button type="primary" block @click="visibles.attachment = true">
					<check-outlined v-if="modelRef.attachments?.length" />
					<plus-outlined v-else />
				</a-button>
			</div>
		</div>

		<template #footer>
			<a-button @click="cancel">取消</a-button>
			<a-button type="primary" @click="sendRequest">保存</a-button>
		</template>
	</a-modal>
	<!-- 附件上传 -->
	<file-upload-dialog v-model:visible="visibles.attachment" v-model:files="attachments" />
</template>
<script setup lang="ts">
	import {reactive, ref, watch, onBeforeMount,watchEffect} from 'vue'
	import {VxeGridProps} from 'vxe-table'
	import {message} from 'ant-design-vue'
	import {CheckOutlined, ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import {deviceEnergyWarningById, getHouseDeliveryGetNoe, houseSetting, getOneRenterInfo, meterReadRecordLastRecord} from '@/api/contract'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import dayjs from 'dayjs'
	import {METER_DEVICE_MAP} from '@/constant/device'
	import {defaultMeters} from '@/interface/contract'
	import FileUploadDialog from '@/components/common/file-upload-dialog.vue'
	import {Img} from 'yuxin-base/src/types'

	const modelRef = reactive<any>({
		comment: '',
		attachments: '',
		articles: [],
		meters: defaultMeters()
	})
	const visibles = reactive<any>({
		attachment: false
	})
	const attachments = ref<Img[]>([])
	const delivery = ref<any>(false)
	const props = defineProps<{
		visible: boolean
		id?: string
		earlyData?: any[]
		houseId?: string
		energyDictArr?: any[]
		data?: any
		type?: any // 3 业主合同退租
		isResubmit?: boolean
		getDelivery?: any
	}>()

	const checkList = reactive<any>([])

	watchEffect(() => {
		modelRef.attachmentDtos = attachments.value
		modelRef.attachments = attachments.value.map(o => o.id)
	})
	onBeforeMount(async ()=>{
		await getDicList()
	})
	watch([() => props.visible, () => props.id], async (newVal, oldVal) => {

		if (newVal[0] && newVal[1]) {
			await getDicList()
			if (props?.type === 2) {
				oneRenterInfo()
			} else {
				if (props.getDelivery?.meters) {
					modelRef.comment = props.getDelivery.comment || ''
					modelRef.articles = props.getDelivery.articles || []
					imgfiles.imgLiist = props.getDelivery.attachmentDtos || []
					attachments.value = props.getDelivery.attachmentDtos || []
					modelRef.meters = props.getDelivery.meters || []
					// 如果有id需要把id也是设置进去 !!!
					if (props.getDelivery.id) modelRef.id = props.getDelivery.id
					let num = setTimeout(() => {
						getCheckData(modelRef.articles)
						clearTimeout(num)
					}, 100)
				} else {
					getDelivery()
				}
			}

			// 数据回显
			if (props.data) {
				// 回显之前先清除原有的数据 防止数据污染
				gridOptions.data = []
				console.log('props.data==========', props.data)
				if (JSON.stringify(props.data) === '{}') {
					reset()
				} else {
					for (let key in props.data) {
						console.log(key)
						modelRef[key] = props.data[key]
					}
				}
			}
			energyGrid.value?.commitProxy('reload')
			if (props?.isResubmit) {
				return
			}
			if ((!modelRef.hasOwnProperty('earlyData') && !modelRef.hasOwnProperty('meterReadRecordDtos')) || (!modelRef.energyDictArr.length && !modelRef.earlyData.length && !modelRef.meterReadRecordDtos.length) || props.data?.energyDictArr.length) {
				// (业主合同不用调用这个接口)
				if([3].includes(props.type)) return
				//请求数据'
				gethouseSetting()
				// getEarlyData()
			} else {
				//能耗预警
				earlyData.value = [...modelRef.earlyData] || []
				//预付费
				energyList.value = [...modelRef.meterReadRecordDtos] || []
				//后付费
				postpaData.value = [...modelRef.energyDictArr] || []
				if (earlyData.value.length) supplementary()
			}
		}
	})
	const energyList = ref<any>([])
	const gethouseSetting = () => {
		if (props.id) {
			houseSetting(props.id).then(res => {
				earlyData.value = res.data?.deviceEnergyWarnings || []
				postpaData.value = res.data?.deviceLastReadRecords || []
				energyList.value = res.data?.meterReadRecords || []
				energyDictArrList.value = res.data?.energyCostRoomSettings || []
				if (earlyData.value.length) supplementary()
			})
		}
	}
	const energyDictArrList = ref<any>([])
	const earlyData = ref<any[]>([])

	//获取能耗费预警列表
	const getEarlyData = () => {
		deviceEnergyWarningById(props.id).then(res => {
			earlyData.value = res.data
			supplementary()
		})
	}
	const getID = id => {
		return feeSubject.value.find(o => o.id === id).name
	}
	const getMoneyByID = id => {
		const feeSubject = energyDictArrList.value.find(o => o.feeSubjectId === id) || {}
		return parseFloat(feeSubject.price || 0)
	}
	const imgfiles = reactive<any>({
		imgLiist: []
	})

	const getDelivery = () => {
		//新签1 退租2
		let params = {
			id: props.id,
			type: 1
		}
		getHouseDeliveryGetNoe(params).then((res: any) => {
			if (res.data) {
				modelRef.id = res.data.id || null
				modelRef.comment = res.data.comment || ''
				modelRef.articles = res.data.articles || []
				imgfiles.imgLiist = res.data.attachmentDtos || []
				attachments.value = res.data.attachmentDtos || []
			}
			let number = setTimeout(() => {
				/** 标记损坏的物品并禁用勾选 */
				(modelRef.articles || []).forEach(i => {
					i.isDisabledBroken = Boolean(i.isBroken)
				})
				getCheckData(modelRef.articles)
				clearTimeout(number)
			}, 100)
		})
	}
	const oneRenterInfo = () => {
		let params = {
			id: props.houseId,
			type: 1
		}
		getOneRenterInfo(params).then((res: any) => {
			if (res.data) {
				modelRef.id = res.data.id || null
				modelRef.comment = res.data.comment || ''
				modelRef.articles = res.data.articles || []
				imgfiles.imgLiist = res.data.attachmentDtos || []
				attachments.value = res.data.attachmentDtos || []
			}
			getCheckData(modelRef.articles)
		})
	}
	const checkboxRow = () => {
		let list = [],
			arr = grid.value.getTableData().tableData
		for (let i in arr) {
			if (arr[i].isBroken) {
				list.push(arr[i])
			}
		}
		grid.value.setCheckboxRow(list, true)
	}
	const getCheckData = (list: any) => {
		checkList.value = list
		insertEvent(-1)
	}
	const insertEvent = async (row: any) => {
		const $table = grid.value
		const list = grid.value?.getTableData()?.tableData || []
		if (list.length) {
			for (let item of list) {
				let index = checkList.value.findIndex((o: {id: any}) => item.id === o.id)
				if (index !== -1) {
					checkList.value.splice(index, 1)
				}
			}
		}

		const {row: newRow} = await $table.insertAt(checkList.value, row)
		await $table.setEditCell(newRow, 'name')
		checkboxRow()
	}
	const emit = defineEmits(['update:visible', 'success', 'update:data'])
	const cancel = () => {
		// reset()
		emit('update:visible', false)
	}
	const selectChangeEvent = ({checked, rowIndex}: any) => {
		const $table = grid.value
		grid.value.getTableData().tableData[rowIndex].isBroken = checked ? 1 : 0
	}
	const feeSubject = ref<any>([])

	const getDicList = async() => {
		// 获取费用科目列表
		await settingApi.getDicListByLabelAll('FEESUBJECT@ENERGY').then(({data}) => {
			feeSubject.value = data[0].metaList
		})
	}

	const sendRequest = () => {
		let list = grid.value.getTableData().tableData
		modelRef.articles = [...grid.value.getTableData().tableData]
		// modelRef.transferWhArticles = [...grid.value.getTableData().tableData]
		let energyDictArrs: any = []
		let earlyLists: any = []
		let tableData: any = []
		modelRef.attachments = JSON.stringify(attachments.value.map(o => o.id))
		if (earlyDataCheck()) {
			return
		}
		if (checkEnergyDictArr()) {
			return
		}
		if (check()) {
			return
		}
		tableData = energyList.value || []
		modelRef.meterReadRecordDtos = tableData
		//预警
		if (earlyData.value.length) {
			for (let o of earlyData.value) {
				let info = {
					amount: parseFloat(((o.lastRead - o.firstRead) * getMoneyByID(o.feeSubjectId)).toFixed(2)),
					beginDate: o.beginDate,
					endDate: o.endDate,
					feeDirection: 1,
					feeSubjectId: o.feeSubjectId,
					feeSubjectName: getID(o.feeSubjectId),
					id: o.id,
					energyWarningId: o.id,
					notOccurredMoney: parseFloat(((o.lastRead - o.firstRead) * getMoneyByID(o.feeSubjectId)).toFixed(2)),
					lastRead: o.lastRead,
					firstRead: o.firstRead
				}
				earlyLists.push(info)
			}
		}
		//后付费
		if (postpaData.value.length) {
			for (let o of postpaData.value) {
				const sameSubject = (props.data?.energyDictArr || []).some(e=>e.feeSubjectId === o.feeSubjectId)
				const sameId = (props.data?.energyDictArr ||[]).find(e=>e.feeSubjectId === o.feeSubjectId)?.id
				let item = {
					amount: parseFloat(((o.lastRead - o.firstRead) * getMoneyByID(o.feeSubjectId)).toFixed(2)),
					beginDate: o.beginDate,
					endDate: o.endDate,
					feeDirection: 1,
					feeSubjectId: o.feeSubjectId,
					feeSubjectName: getID(o.feeSubjectId),
					id: sameSubject? sameId : o.id,
					energyWarningId: o.id,
					notOccurredMoney: parseFloat(((	o.lastRead - o.firstRead) * getMoneyByID(o.feeSubjectId)).toFixed(2)),
					lastRead: o.lastRead,
					firstRead: o.firstRead,
					deviceId: o.deviceId,
					deviceType: o.deviceType
				}
				energyDictArrs.push(item)
			}
		}
		modelRef.earlyData = earlyLists
		modelRef.energyDictArr = energyDictArrs
		emit('success', modelRef)
		emit('update:data', modelRef.value)
		cancel()
	}
	const isUpdate = ref<boolean>(false)
	const inpudeShow = ref<any>([])
	//能耗费预警读数是否可编辑
	const supplementary = () => {
		earlyData.value.forEach(o => {
			let firstRead = false,
				lastRead = false
			if (!o.firstRead || (o.lastRead && o.firstRead > o.lastRead)) {
				firstRead = true
			}
			if (!o.lastRead || o.firstRead > o.lastRead) {
				lastRead = true
			}
			inpudeShow.value.push({
				firstRead: firstRead,
				lastRead: lastRead
			})
		})
		isUpdate.value = true
	}
	const early = ref()
	const earlyWarning = reactive<VxeGridProps>({
		size: 'small',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		scrollX: {enabled: false},
		columns: [
			{
				title: '租客姓名',
				minWidth: 120,
				field: 'renterName'
			},
			{
				title: '月份',
				width: 80,
				field: 'months'
			},
			{
				title: '费用类型',
				minWidth: 120,
				slots: {
					default: 'feeSubject'
				}
			},
			{
				title: '期初抄表日期',
				width: 160,
				field: 'beginDate'
			},
			{
				title: '期末抄表日期',
				width: 160,
				field: 'endDate'
			},
			{
				title: '期初读数',
				width: 140,
				slots: {
					default: 'openRead'
				}
			},
			{
				title: '期末读数',
				width: 140,
				slots: {
					default: 'endRead'
				}
			}
		]
	})
	const grid = ref()
	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		maxHeight: '200',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		checkboxConfig: {
			trigger: 'row',
			checkStrictly: true,
			highlight: true,
			checkMethod({row}) {
				return !(3 === props.type && row.isDisabledBroken)
			}
		},
		columns: [
			{
				title: '种类',
				minWidth: 100,
				align: 'left',
				field: 'typeName'
			},
			{
				title: '物品名称',
				minWidth: 100,
				align: 'left',
				field: 'configName'
			},
			{
				title: '价格(元)',
				minWidth: 80,
				align: 'left',
				field: 'price'
			},
			{
				title: '数量',
				minWidth: 50,
				align: 'center',
				field: 'count'
			},
			{
				title: '是否损坏',
				width: 150,
				align: 'center',
				type: 'checkbox'
			}
		],
		data: []
	})

	// 能源费列表
	const queryPostpaData = () => {
		meterReadRecordLastRecord({roomId: props.houseId}).then(res => {
			postpaData.value = res.data || []
		})
	}
	const deviceMap = {1: '冷水费', 2: '中水费', 3: '热水费', 4: '电费', 5: '门锁费'}
	const postpaid = ref()
	const postpaData = ref<any[]>([])
	const postpaidOptions = reactive<VxeGridProps>({
		size: 'small',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '能耗类型',
				minWidth: 100,
				align: 'center',
				slots: {
					default: 'feeSubject'
				}
			},
			{
				title: '上期取值时间',
				minWidth: 100,
				align: 'center',
				field: 'beginDate'
			},
			{
				title: '上期读数',
				minWidth: 100,
				align: 'center',
				slots: {
					default: 'firstRead'
				}
			},
			{
				title: '读数取值时间',
				minWidth: 100,
				align: 'center',
				field: 'endDate'
			},
			{
				title: '退租确认读数',
				minWidth: 100,
				align: 'center',
				slots: {
					default: 'lastRead'
				}
			}
		]
	})
	const energyGrid = ref()
	const energyOptions = reactive<VxeGridProps>({
		size: 'small',
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '能耗类型',
				minWidth: 100,
				align: 'center',
				slots: {
					default: 'deviceType'
				}
			},
			{
				title: '读数取值时间',
				minWidth: 100,
				align: 'center',
				field: 'ts',
				slots: {
					default: 'ts'
				}
			},
			{
				title: '退租确认读数',
				minWidth: 100,
				align: 'center',
				slots: {
					default: 'amount'
				}
			}
		]
	})

	const check = () => {
		// 检验是否有 读数 未输入
		let temp = false
		if (!energyList.value.length) {
			return temp
		}
		energyList.value.some((e: any) => {
			console.log('e.amount===', e.amount)
			if (e.amount === null) {
				message.error('请输入读数')
				temp = true
				return temp
			}
		})

		return temp
	}
	const checkEnergyDictArr = () => {
		let temp = false
		// 检验是否有 读数 未输入
		if (!postpaData.value.length) {
			return temp
		}
		for (let e of postpaData.value) {
			if (e.firstRead === null || e.firstRead === '' || e.lastRead === null || e.lastRead === '') {
				message.error('请输入读数')
				temp = true
				return temp
			}
		}
		return temp
	}

	const earlyDataCheck = () => {
		// 检验是否有 读数 未输入
		if (!earlyData.value.length) {
			return false
		}
		for (let e of earlyData.value) {
			if (e.firstRead === null || e.firstRead === '' || e.lastRead === null || e.lastRead === '') {
				message.error('请输入读数')
				return true
			}
		}
		return false
	}

	// 重置表单
	const reset = () => {
		modelRef.comment = ''
		modelRef.articles = []
		modelRef.attachments = ''
		modelRef.meters = defaultMeters()
		modelRef.meterReadRecordDtos = []
		modelRef.earlyData = []
		modelRef.energyDictArr = []
		modelRef.attachmentDtos = []
	}
</script>

<style lang="less">
	.delivery-note .ant-modal-content {
		.ant-modal-body {
			height: 600px;
			overflow-y: auto;
		}
		.width-33 {
			width: 33.33%;
		}
		.tab-box {
			.right-btn {
				position: absolute;
				right: 0;
				top: 0;
			}
		}

		.d-module-title {
			margin-bottom: 5px;
			margin-top: 15px;
			.tip-text {
				margin-left: 10px;
			}
		}
	}
</style>
